from typing import List

from sqlalchemy.orm import Session

from server.app.cloud_ide.model import IdeRegistry
from server.app.cloud_ide.schema.ide_registry.request.ide_registry_create_request import IdeRegistryCreateRequest
from server.app.cloud_ide.schema.ide_registry.request.ide_registry_update_request import IdeRegistryUpdateRequest
from server.framework.core.logger import logger


class IdeRegistryService:
    def find_ide_registry_by_name(self, db: Session, name: str) -> IdeRegistry:
        return db.query(IdeRegistry).filter(IdeRegistry.name == name).first()

    def get_all_ide_registry(self, db: Session) -> List[IdeRegistry]:
        results = db.query(IdeRegistry).all()
        return results

    def get_ide_registry_by_id(self, db: Session, id: str) -> IdeRegistry:
        entity = db.query(IdeRegistry).filter(id == IdeRegistry.id).one()
        return entity

    def get_ide_registry_list(self, db: Session, name: str, enable: int,
                              page_size: int, current_page: int):
        query = db.query(IdeRegistry)
        if name is not None:
            query = query.filter(IdeRegistry.name.like("%" + name + "%"))
        if enable is not None:
            query = query.filter(IdeRegistry.enable == enable)
        total = query.count()
        items = query.limit(page_size).offset((current_page - 1) * page_size).all()
        return items, total

    def create_ide_registry(self, db: Session, data: IdeRegistryCreateRequest) -> bool:
        try:
            entity = IdeRegistry(**data.dict())
            db.add(entity)
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False

    def delete_ide_registry(self, db: Session, ids: list) -> bool:
        try:
            db.query(IdeRegistry).filter(IdeRegistry.id.in_(ids)).delete(synchronize_session=False)
            db.commit()
        except Exception as e:
            logger.error(e)
            return False

    def update_ide_registry(self, db: Session, data: IdeRegistryUpdateRequest) -> bool:
        try:
            db.query(IdeRegistry).filter(IdeRegistry.id == data.id).update(data.dict())
            db.commit()
            return True
        except Exception as e:
            logger.error(e)
            return False
